package com.sicheng.lc.lc笔试._360篇;

import com.sicheng.algorithm.node.ListNode;

/**
 * @author zsc
 * @version 1.0
 * @date 2022/9/4 0:03
 */
public class 合并有序链表 {
    ListNode merge(ListNode l1, ListNode l2) {
        if (l1 == null)
            return l2;
        if (l2 == null)
            return l1;

        if (l1.val > l2.val) {
            ListNode t = l1;
            l1 = l2;
            l2 = t;
        }

        ListNode head = l1, t = l1;

        while (t.next != null && l2 != null) {
            if (t.next.val > l2.val) {
                ListNode next = l2.next;
                l2.next = t.next;
                t.next = l2;
                l2 = next;
            }
            t = t.next;
        }
        if (l2 != null)
            t.next = l2;

        return head;

    }
}
